<template>
  <div class="app-container">
    <avue-crud
      ref="curd"
      v-model="form"
      v-loading="listLoading"
      :option="option"
      :data="list"
      :page="page"
      :before-open="beforeOpen"
      @row-save="rowSave"
      @row-update="rowUpdate"
      @row-del="rowDel"
      @refresh-change="getList"
    >
      <template #expand="{ row }">
        <el-upload
          :action="'/api/Stock/upload?isUpdate=false&bookID=' + row.stockId"
          list-type="picture-card"
          :file-list="row.pictures"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          :multiple="true"
        >
          <i class="el-icon-plus" />
          <div slot="file" slot-scope="{file}" style="height: 100%;">
            <div style="width: 50%">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-edit" />
                </span>
                <!-- <span
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <i class="el-icon-download" />
                </span> -->
                <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete" />
                </span>
              </span>
            </div>
            <div style="position: absolute;top: 12px;right: 0px;width: 155px;text-align: left;">
              <div>股票代码:{{ file.stockCode }}</div>
              <div>股票价格:{{ file.stockPrice }}</div>
              <div>平仓股票代码:{{ file.closingCode }}</div>
              <div>平仓股价:{{ file.closePrice }}</div>
            </div>
            <div v-if="file.stockCode" style="position: absolute; bottom: 0px; left: 0; width: 100%; text-align: center; color: white; background-color: gray;">
              {{ file.stockCode }}
            </div>
          </div>
        </el-upload>
      </template>
      <template slot="stockLstsForm">
        <el-upload
          :action="'/api/Stock/upload?isUpdate=false&bookID=' + form.stockId"
          list-type="picture-card"
          :file-list="form.pictures"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          :multiple="true"
        >
          <i class="el-icon-plus" />
          <div slot="file" slot-scope="{file}" style="height: 100%;">
            <div style="width: 50%">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-edit" />
                </span>
                <!-- <span
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <i class="el-icon-download" />
                </span> -->
                <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete" />
                </span>
              </span>
            </div>
            <div style="position: absolute;top: 12px;right: 0px;width: 155px;text-align: left;">
              <div>股票代码:{{ file.stockCode }}</div>
              <div>股票价格:{{ file.stockPrice }}</div>
              <div>平仓股票代码:{{ file.closingCode }}</div>
              <div>平仓股价:{{ file.closePrice }}</div>
            </div>
            <div v-if="file.stockCode" style="position: absolute; bottom: 0px; left: 0; width: 100%; text-align: center; color: white; background-color: gray;">
              {{ file.stockCode }}
            </div>
          </div>
        </el-upload>
      </template>
    </avue-crud>
    <el-dialog :visible.sync="dialogVisible">
      <el-button type="success" @click="saveStock">保存</el-button>
      <el-button type="primary" @click="dialogVisible = !dialogVisible">取消</el-button>
      <hr>
      <avue-form ref="editForm" v-model="editForm" :option="formOption" />
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createArticle, updateArticle, deleteArticle, deleteFile, updateStock, getId } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { get_formOption, get_option } from './js/options'
import { mapGetters } from 'vuex'

export default {
  name: 'Deal',
  directives: { waves },
  data() {
    return {
      listLoading: true,
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 20
      },
      list: [],
      form: {},
      editForm: {},
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false
    }
  },
  computed: {
    ...mapGetters(['userId', 'token']),
    option() {
      let op = get_option()
      op.expandRowKeys = []
      if (this.list.length > 0) {
        op.expandRowKeys.push(this.list[0].id)
      }
      return op
    },
    formOption() {
      let op = get_formOption()
      return op
    },
    headers() {
      return {
        Authorization: 'Bearer ' + this.token
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    saveStock() {
      updateStock(this.editForm).then(() => {
        this.$notify({
          title: 'Success',
          message: '保存成功！',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    handleAvatarSuccess(res, file) {
      file.url = res
    },
    beforeAvatarUpload() {

    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
      this.$refs.editForm.resetForm()
      this.$nextTick(() => {
        this.editForm = file
      })
    },
    handleRemove(file, fileList) {
      this.$confirm(`确定移除${file.name}？`).then(() => {
        deleteFile(file.url).then(() => {
          this.getList()
        })
      })
    },
    async beforeOpen(done, type) {
      // console.log(type)
      if (type === 'add') {
        if (this.list.length > 0) {
          this.form.total = this.list[0].total
        }
        let res = await getId()
        this.$set(this.form, 'stockId', res.data)
      }
      done()
    },
    // 获取数据
    getList() {
      this.listLoading = true
      fetchList({ ... this.page, pageIndex: this.page.currentPage, userId: this.userId }).then(response => {
        this.list = response.data.resultList
        this.list.forEach(o => {
          let pictures = o.stockLsts.map(o2 => { return { ...o2, name: o2.stockCode, url: o2.picture } })
          this.$set(o, 'pictures', pictures)
        })
        this.page.total = response.data.totalPage
        this.listLoading = false
        this.$refs.curd.doLayout()
      })
    },
    // 校验与新增数据
    rowSave(form, done, loading) {
      loading()
      form.userId = this.userId
      form.stockLsts = []
      createArticle(form).then(() => {
        done()
        this.$notify({
          title: 'Success',
          message: '新增成功！',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    // 校验与更新数据
    rowUpdate(form, index, done, loading) {
      loading()
      updateArticle(form).then(() => {
        done()
        this.$notify({
          title: 'Success',
          message: '更新成功！',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    rowDel(form, index) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteArticle(form.id).then(() => {
          this.list.splice(index, 1)
          this.getList()
        })
        this.success('删除成功!')
      }).catch(() => { })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: calc(48%) !important;
}
</style>
